/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.table.ColumnType;
import com.je.common.base.constants.table.TableType;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.table.BuildingSqlFactory;
import com.je.common.base.util.*;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.service.table.MetaTableKeyService;
import com.je.meta.service.table.MetaTableTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-09-18 11:23
 * @description: 资源表键服务实现
 */
@Service
public class MetaTableKeyServiceImpl implements MetaTableKeyService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaTableTraceService metaTableTraceService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DynaCache dynaCache;

    @Override
    @Transactional
    public void deleteKeyMeta(String tableCode, List<DynaBean> keys) {
        String[] delIds = new String[keys.size()];
        for (int i = 0; i < keys.size(); i++) {
            DynaBean tc = keys.get(i);
            delIds[i] = tc.getStr("JE_CORE_TABLEKEY_ID");
        }

        List<String> relationResourceIds = new ArrayList<>();
        List<String> byRelationResourceIds = new ArrayList<>();
        List<DynaBean> keysList = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .in("JE_CORE_TABLEKEY_ID", delIds));
        for (DynaBean key : keysList) {
            relationResourceIds.add(key.getStr("TABLEKEY_TABLECODE"));
            byRelationResourceIds.add(key.getStr("TABLEKEY_LINKTABLE"));
        }
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", tableCode));

        String resourcetableParenttablecodes = table.getStr("RESOURCETABLE_PARENTTABLECODES");
        if (!StringUtil.isEmpty(resourcetableParenttablecodes)) {
            String[] ids = resourcetableParenttablecodes.split(ArrayUtils.SPLIT);
            List<String> isList = Arrays.asList(ids);
            List<String> ddlList = new ArrayList<String>(isList);
            for (String byTableCode : byRelationResourceIds) {
                ddlList.remove(byTableCode);
            }
            StringBuffer parentCodes = new StringBuffer();
            for (int i = 0; i < ddlList.size(); i++) {
                String parentCode = ddlList.get(i);
                parentCodes = parentCodes.append(parentCode);
                if (i != ddlList.size() - 1) {
                    parentCodes = parentCodes.append(",");
                }
            }
            table.setStr("RESOURCETABLE_PARENTTABLECODES", parentCodes.toString());
            metaService.update(table);
        }

        List<DynaBean> tablesList = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE", byRelationResourceIds));

        for (DynaBean parentTable : tablesList) {
            String resourcetableChildtablecodes = parentTable.getStr("RESOURCETABLE_CHILDTABLECODES");
            if (!StringUtil.isEmpty(resourcetableChildtablecodes)) {
                String[] childIds = resourcetableChildtablecodes.split(ArrayUtils.SPLIT);
                List<String> tempList = Arrays.asList(childIds);
                List<String> childList = new ArrayList<String>(tempList);
                childList.remove(tableCode);
                StringBuffer childCodes = new StringBuffer();
                for (int i = 0; i < childList.size(); i++) {
                    String childCode = childList.get(i);
                    childCodes = childCodes.append(childCode);
                    if (i != childList.size() - 1) {
                        childCodes = childCodes.append(",");
                    }
                }
                parentTable.setStr("RESOURCETABLE_CHILDTABLECODES", childCodes.toString());
                metaService.update(parentTable);
            }
        }


//        if("1".equals(key.get("RESOURCETABLE_ISCREATE"))){
//            String resourcetableParenttablecodes = key.getStr("RESOURCETABLE_PARENTTABLECODES");
//        }

        if (delIds.length > 0) {
            metaService.executeSql("DELETE FROM JE_CORE_TABLEKEY WHERE JE_CORE_TABLEKEY_ID IN ({0})", Arrays.asList(delIds));
        }
    }

    @Override
    public String requireDeletePhysicalKeyDDL(String tableCode, List<DynaBean> keys) {
        String delSql = BuildingSqlFactory.getDdlService().getDeleteKeySql(tableCode, keys);
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().ne("RESOURCETABLE_TYPE", "MODULE")
                .eq("RESOURCETABLE_TABLECODE", tableCode));
        if (StringUtil.isNotEmpty(delSql) && table != null && !TableType.VIEWTABLE.equals(table.getStr("RESOURCETABLE_TYPE"))) {
            return delSql;
        }
        return null;
    }

    /**
     * 修改表格键
     *
     * @param dynaBean
     * @param strData
     * @return
     */
    @Override
    public int doUpdateList(DynaBean dynaBean, String strData) throws APIWarnException {
        String tableCode = "JE_CORE_TABLEKEY";
        String pkName = "JE_CORE_TABLEKEY_ID";
        Map<String, DynaBean> oldMaps = new HashMap<String, DynaBean>();
        int rows = 0;
        dynaBean.table(tableCode);
        String[] ids = JsonUtil.jsonSqlToIdsStr(dynaBean, strData);
        List<Map> sqlMapList = JsonUtil.fromJsonArray(strData);
        String[] updateSqls = new String[sqlMapList.size()];
        String tablekeyTablecode = null;
        List<Map<String, Object>> keys = new ArrayList<>();
        for (int i = 0; i < sqlMapList.size(); i++) {
            Map sqlMap = sqlMapList.get(i);

            if ("Unique".equals(sqlMap.get("TABLEKEY_TYPE"))) {
                String tablekeyColumncode = sqlMap.get("TABLEKEY_COLUMNCODE").toString();
                if (StringUtil.isEmpty(tablekeyTablecode)) {
                    tablekeyTablecode = sqlMap.get("TABLEKEY_TABLECODE").toString();
                    keys = metaService.selectSql("SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_name = {0}", tablekeyTablecode);
                }

                for (int j = 0; j < keys.size(); j++) {
                    Map<String, Object> key = keys.get(j);
                    String columnName = key.get("COLUMN_NAME").toString();
                    if (tablekeyColumncode.equals(columnName)) {
                        if (!StringUtil.isEmpty(key.get("TABLE_NAME"))) {
                            if (StringUtil.isEmpty(key.get("POSITION_IN_UNIQUE_CONSTRAINT"))) {
                                throw new APIWarnException(MessageUtils.getMessage("key.multi"), "201", new Object[]{dynaBean});
                            }
                        }
                    }
                }
            }

            String sql = BuildingSqlFactory.getSqlService().getUpdateSql(tableCode, pkName, sqlMap);
            updateSqls[i] = sql;
            DynaBean oldBean = metaService.selectOneByPk("JE_CORE_TABLEKEY", sqlMap.get(pkName).toString());
            oldMaps.put(sqlMap.get(pkName) + "", oldBean);
        }
        rows = updateSqls.length;
        for (String sql : updateSqls) {
            metaService.executeSql(sql);
        }
        List<DynaBean> newBeans = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .in("JE_CORE_TABLEKEY_ID", ids));
        for (DynaBean bean : newBeans) {
            String pk = bean.getStr(pkName);
            DynaBean oldBean = oldMaps.get(pk);
            metaTableTraceService.saveTableTrace("JE_CORE_TABLEKEY", oldBean, bean, "UPDATE", oldBean.getStr("TABLEKEY_RESOURCETABLE_ID"), oldBean.getStr("TABLEKEY_ISCREATE"));
        }
        return rows;
    }

    /**
     * 同步主表，主键类型
     *
     * @param dynaBean
     * @param strData
     * @return
     */
    @Override
    public void syncMainTablePrimaryType(DynaBean dynaBean, String strData) throws APIWarnException {
        JSONArray data = JSONArray.parseArray(strData);
        for (Object obj : data) {
            JSONObject item = JSONObject.parseObject(String.valueOf(obj));
            String tableKeyType = item.getString("TABLEKEY_TYPE");
            if (!"Foreign".equals(tableKeyType)) {
                continue;
            }
            String linkTable = item.getString("TABLEKEY_LINKTABLE");
            String lineColumnCode = item.getString("TABLEKEY_LINECOLUMNCODE");
            String resourceTableId = item.getString("TABLEKEY_RESOURCETABLE_ID");
            String columnCode = item.getString("TABLEKEY_COLUMNCODE");
            if (Strings.isNullOrEmpty(linkTable) || Strings.isNullOrEmpty(lineColumnCode)
                    || Strings.isNullOrEmpty(resourceTableId) || Strings.isNullOrEmpty(columnCode)) {
                continue;
            }
            DynaBean targetColumn = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE",linkTable).eq("TABLECOLUMN_CODE",lineColumnCode));
            if(targetColumn==null){
                continue;
            }
            String tableColumnType = targetColumn.getStr("TABLECOLUMN_TYPE");
            String tableColumnLength = targetColumn.getStr("TABLECOLUMN_LENGTH");

            DynaBean column = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", resourceTableId).eq("TABLECOLUMN_CODE", columnCode));
            if (column != null) {
                if(ColumnType.ID.equals(tableColumnType)){
                    column.setStr("TABLECOLUMN_TYPE", ColumnType.VARCHAR50);
                }else if(ColumnType.CUSTOMFOREIGNKEY.equals(tableColumnType) || ColumnType.CUSTOMID.equals(tableColumnType)){
                    column.setStr("TABLECOLUMN_TYPE", ColumnType.CUSTOMFOREIGNKEY);
                    column.setStr("TABLECOLUMN_LENGTH",tableColumnLength);
                }else{
                    column.setStr("TABLECOLUMN_TYPE", tableColumnType);
                    column.setStr("TABLECOLUMN_LENGTH",tableColumnLength);
                }
            }
            metaService.update(column);
        }
    }

    /**
     * 生成删除键DDL
     *
     * @param dynaBean
     * @param keys
     * @param ddl
     * @return
     */
    @Override
    public String generateDeleteKeyDDL(DynaBean dynaBean, List<DynaBean> keys, String ddl) {
        String tableCode = dynaBean.getStr("RESOURCETABLE_TABLECODE");
        String sqlDdl = generateKey(tableCode, keys, ddl);
        return sqlDdl;
    }

    /**
     * 执行DDL
     *
     * @param sqlDDl
     * @param table
     * @return
     */
    @Override
    public boolean funcDDL(String sqlDDl, DynaBean table, String isDeleteDdl) {
        if (StringUtil.isNotEmpty(sqlDDl) && table != null && !TableType.VIEWTABLE.equals(table.getStr("RESOURCETABLE_TYPE"))) {
            if ("1".equals(isDeleteDdl)) {
                metaService.executeSql(sqlDDl);
                return true;
            }
        }
        return false;
    }

    /**
     * 根据DDL状态修改元数据
     *
     * @param dynaBean
     * @param keys
     */
    @Override
    public void updateMeta(DynaBean dynaBean, List<DynaBean> keys) {
        for (DynaBean key : keys) {
            metaTableTraceService.saveTableTrace("JE_CORE_TABLEKEY", key, key, "DELETE", key.getStr("TABLEKEY_RESOURCETABLE_ID"), key.getStr("TABLEKEY_ISCREATE"));
        }
        String tableCode = dynaBean.getStr("RESOURCETABLE_TABLECODE");
        //删除键元数据
        deleteKeyMeta(tableCode, keys);
        tableCache.removeCache(tableCode);
        dynaCache.removeCache(tableCode);
    }

    /**
     * 根据键id获取键信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<DynaBean> selectTableKeyByKeyId(String ids) {
        String[] split = ids.split(ArrayUtils.SPLIT);
        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .in("JE_CORE_TABLEKEY_ID", split));
        return keys;
    }

    @Override
    public String checkParameter(String strData) {
        JSONArray data = JSONArray.parseArray(strData);
        List<DynaBean> keyList = new ArrayList<>();
        if (data != null && data.size() > 0) {
            String tableId = data.getJSONObject(0).getString("TABLEKEY_RESOURCETABLE_ID");
            keyList = metaService.select(ConditionsWrapper.builder()
                    .table("JE_CORE_TABLEKEY")
                    .eq("TABLEKEY_RESOURCETABLE_ID", tableId));
            if (keyList.isEmpty()) {
                return null;
            }
        }
        for (Object obj : data) {
            JSONObject item = JSONObject.parseObject(String.valueOf(obj));
            String TABLEKEY_TYPE = item.getString("TABLEKEY_TYPE");
            /**
             * 主键类型的表单key只有一个
             */
            if ("Primary".equals(TABLEKEY_TYPE)) {
                for (DynaBean dynaBean : keyList) {
                    String dbKey = dynaBean.getStr("TABLEKEY_TYPE");
                    if ("Primary".equals(dbKey)) {
                        return MessageUtils.getMessage("table.id.multi");
                    }
                }
            }
            /**
             * 同一个关联表的同一个字段只能存在一次
             */
            String TABLEKEY_COLUMNCODE = item.getString("TABLEKEY_COLUMNCODE");
            String TABLEKEY_LINKTABLE = (item.getString("TABLEKEY_LINKTABLE") == null ? "" : item.getString("TABLEKEY_LINKTABLE")).toUpperCase();
            String TABLEKEY_LINECOLUMNCODE = item.getString("TABLEKEY_LINECOLUMNCODE");
            if (StringUtil.isEmpty(TABLEKEY_COLUMNCODE)) {
                return MessageUtils.getMessage("table.key.columncode.conNotEmpty");
            }
            if (StringUtil.isEmpty(TABLEKEY_LINKTABLE)) {
                return MessageUtils.getMessage("table.key.linktable.conNotEmpty");
            }
            if (StringUtil.isEmpty(TABLEKEY_LINECOLUMNCODE)) {
                return MessageUtils.getMessage("table.key.linecolumncode.conNotEmpty");
            }
            for (DynaBean dynaBean : keyList) {
                if (!Strings.isNullOrEmpty(dynaBean.getStr("JE_CORE_TABLEKEY_ID"))) {
                    continue;
                }
                String dbKey = dynaBean.getStr("TABLEKEY_TYPE");
                if (!"Primary".equals(dbKey) && StringUtil.isNotEmpty(TABLEKEY_COLUMNCODE)) {
                    String dbLinkTable = (dynaBean.getStr("TABLEKEY_LINKTABLE") == null ? "" : dynaBean.getStr("TABLEKEY_LINKTABLE")).toUpperCase();
                    String dbLinkColumn = dynaBean.getStr("TABLEKEY_LINECOLUMNCODE");
                    String dbColumCode = dynaBean.getStr("TABLEKEY_COLUMNCODE");
                    if (TABLEKEY_LINKTABLE.equals(dbLinkTable) && TABLEKEY_LINECOLUMNCODE.equals(dbLinkColumn) && TABLEKEY_COLUMNCODE.equals(dbColumCode)) {
                        return MessageUtils.getMessage("table.key.link.exits", TABLEKEY_COLUMNCODE);
                    }
                }

            }
        }
        return null;
    }

    /**
     * 生成DDL返回
     *
     * @param tableCode
     * @param keys
     * @param ddl
     * @return
     */
    private String generateKey(String tableCode, List<DynaBean> keys, String ddl) {
        //删除表字段
        String delSql = BuildingSqlFactory.getDdlService().getDeleteKeySql(tableCode, keys);
        return delSql;
    }

    @Override
    @Transactional
    public void deleteKey(String tableCode, List<DynaBean> keys, String isddl) throws UncategorizedSQLException {
        if (keys == null || keys.size() == 0) {
            return;
        }
        if (isddl.equals("1")) {
            DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().ne("RESOURCETABLE_TYPE", "MODULE")
                    .eq("RESOURCETABLE_TABLECODE", tableCode));
            //删除表字段
            String delSql = BuildingSqlFactory.getDdlService().getDeleteKeySql(tableCode, keys);
            if (StringUtil.isNotEmpty(delSql) && table != null && !TableType.VIEWTABLE.equals(table.getStr("RESOURCETABLE_TYPE"))) {
                for (String sql : delSql.split(";")) {
                    if (!Strings.isNullOrEmpty(sql)) {
                        try {
                            sql = sql.replaceAll("\n", "");
                            metaService.executeSql(sql);
                        } catch (UncategorizedSQLException e) {
                            throw new PlatformException(MessageUtils.getMessage("index.delete.index.error") + e.getCause().getMessage(),
                                    PlatformExceptionEnum.JE_CORE_TABLEINDEX_DELETE_ERROR, new Object[]{sql}, e);
                        } catch (Exception e) {
                            throw new PlatformException(MessageUtils.getMessage("index.delete.wrong") + "," + e.getCause().getMessage(),
                                    PlatformExceptionEnum.JE_CORE_TABLEINDEX_DELETE_ERROR, new Object[]{sql}, e);
                        }
                    }
                }
            }
        }
        //删除键元数据
        deleteKeyMeta(tableCode, keys);

    }

    @Override
    @Transactional
    public void initKeys(DynaBean resourceTable, Boolean isTree) {
        /**ID的键设置*/
        List<DynaBean> keys = new ArrayList<DynaBean>();
        DynaBean pk = new DynaBean("JE_CORE_TABLEKEY", false);
        pk.set("TABLEKEY_CODE", resourceTable.get("RESOURCETABLE_TABLECODE") + "_ID_CODE");
        pk.set("TABLEKEY_COLUMNCODE", resourceTable.get("RESOURCETABLE_TABLECODE") + "_ID");
        pk.set("TABLEKEY_TYPE", "Primary");
        pk.set("TABLEKEY_ISRESTRAINT", "1");
        pk.set("TABLEKEY_CHECKED", "1");
        pk.set("TABLEKEY_CLASSIFY", "SYS");
        pk.set("SY_ORDERINDEX", 0);
        keys.add(pk);
        if (isTree) {
            DynaBean forenignKey = new DynaBean("JE_CORE_TABLEKEY", false);
            forenignKey.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime() + "_PARENT");
            forenignKey.set("TABLEKEY_COLUMNCODE", "SY_PARENT");
            forenignKey.set("TABLEKEY_TYPE", "Inline");
            forenignKey.set("TABLEKEY_CHECKED", "0");
            forenignKey.set("TABLEKEY_LINKTABLE", resourceTable.get("RESOURCETABLE_TABLECODE"));
            forenignKey.set("TABLEKEY_LINECOLUMNCODE", resourceTable.get("RESOURCETABLE_TABLECODE") + "_ID");
            forenignKey.set("TABLEKEY_LINETYLE", "Cascade");
            forenignKey.set("TABLEKEY_ISRESTRAINT", "1");
            forenignKey.set("TABLEKEY_CLASSIFY", "SYS");
            forenignKey.set("SY_ORDERINDEX", 1);
            keys.add(forenignKey);
        }
        String nowDate = DateUtils.formatDateTime(new Date());
        for (DynaBean key : keys) {
            key.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            key.set("SY_CREATETIME", nowDate);
            key.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            key.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            key.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            key.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            key.set("TABLEKEY_ISCREATE", "0");
            key.set("TABLEKEY_TABLECODE", resourceTable.get("RESOURCETABLE_TABLECODE"));
            key.set("TABLEKEY_RESOURCETABLE_ID", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"));
            key.set("SY_PRODUCT_ID", resourceTable.getStr("SY_PRODUCT_ID"));
            key.set("SY_PRODUCT_NAME", resourceTable.getStr("SY_PRODUCT_NAME"));
            metaService.insert(key);
        }
    }

    @Override
    public String checkKeys(List<DynaBean> keys) {
        String errors = "";
        Set<String> keyCodes = new HashSet<String>();
        String tableCode = "";
        Integer primaryCount = 0;
        for (DynaBean key : keys) {
            if (StringUtil.isNotEmpty(key.getStr("TABLEKEY_TABLECODE")) && StringUtil.isEmpty(tableCode)) {
                tableCode = key.getStr("TABLEKEY_TABLECODE");
            }
            String keyStr = "";
            String keyType = key.getStr("TABLEKEY_TYPE");
            if ("Primary".equals(keyType)) {
                if (StringUtil.isEmpty(key.getStr("TABLEKEY_COLUMNCODE"))) {
                    errors = MessageUtils.getMessage("table.id.canotEmpty");
                    break;
                }
                keyStr = keyType + "_" + key.getStr("TABLEKEY_COLUMNCODE");
                primaryCount++;
            }
            if (primaryCount > 1) {
                errors = MessageUtils.getMessage("table.id.multi");
                break;
            }
            if ("Unique".equals(keyType)) {
                if (StringUtil.isEmpty(key.getStr("TABLEKEY_COLUMNCODE"))) {
                    errors = MessageUtils.getMessage("key.column");
                    break;
                }
                keyStr = keyType + "_" + key.getStr("TABLEKEY_COLUMNCODE");
            }
            if ("Foreign".equals(keyType)) {
                DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", key.getStr("TABLEKEY_RESOURCETABLE_ID"));
                if (null != dynaBean) {
                    tableCode = dynaBean.getStr("RESOURCETABLE_TABLECODE");
                }
                if (StringUtil.isEmpty(key.getStr("TABLEKEY_COLUMNCODE"))) {
                    errors = MessageUtils.getMessage("key.column.conNotEmpty", key.getStr("TABLEKEY_COLUMNCODE"));
                    break;
                } else if (StringUtil.isEmpty(key.getStr("TABLEKEY_LINKTABLE"))) {
                    errors = MessageUtils.getMessage("key.table.conNotEmpty", key.getStr("TABLEKEY_COLUMNCODE"));
                    break;
                } else if (StringUtil.isEmpty(key.getStr("TABLEKEY_LINECOLUMNCODE"))) {
                    MessageUtils.getMessage("key.column.field", key.getStr("TABLEKEY_COLUMNCODE"));
                    break;
                }
                //检查构建关联关系的字段类型是否一致
                DynaBean masterTableColumn = metaService.selectOne("JE_CORE_TABLECOLUMN",
                        ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE", key.getStr("TABLEKEY_LINKTABLE")).eq("TABLECOLUMN_CODE", key.getStr("TABLEKEY_LINECOLUMNCODE")));
                DynaBean currentTableColumn = metaService.selectOne("JE_CORE_TABLECOLUMN",
                        ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE", tableCode).eq("TABLECOLUMN_CODE", key.getStr("TABLEKEY_COLUMNCODE")));
                /*if(!contrastColumnType(masterTableColumn,currentTableColumn)){

                }*/
                keyStr = keyType + "_" + key.getStr("TABLEKEY_COLUMNCODE") + "_" + key.getStr("TABLEKEY_LINKTABLE") + "_" + key.getStr("TABLEKEY_LINECOLUMNCODE");
            }
            if ("Inline".equals(keyType)) {
                if (StringUtil.isEmpty(key.getStr("TABLEKEY_COLUMNCODE"))) {
                    errors = MessageUtils.getMessage("key.inline.column");
                    break;
                } else if (StringUtil.isEmpty(key.getStr("TABLEKEY_LINKTABLE"))) {
                    errors = MessageUtils.getMessage("key.inline.table");
                    break;
                } else if (StringUtil.isEmpty(key.getStr("TABLEKEY_LINECOLUMNCODE"))) {
                    errors = MessageUtils.getMessage("key.inline.field");
                    break;
                }
                keyStr = keyType + "_" + key.getStr("TABLEKEY_COLUMNCODE") + "_" + key.getStr("TABLEKEY_LINKTABLE") + "_" + key.getStr("TABLEKEY_LINECOLUMNCODE");
            }
            if (keyCodes.contains(keyStr)) {
                errors = MessageUtils.getMessage("key.this.multi");
                break;
            }
            keyCodes.add(keyStr);
        }
        if (StringUtil.isNotEmpty(errors)) {
            return MessageUtils.getMessage("key.wrong.result", tableCode, errors);
        } else {
            return errors;
        }
    }

    /*private boolean contrastColumnType(DynaBean masterTableColumn, DynaBean currentTableColumn) {
        String masterColumnType = ColumnType.CUSTOM masterTableColumn.getStr("TABLECOLUMN_TYPE");
        String currentColumnType = currentTableColumn.getStr("TABLECOLUMN_TYPE");
        if(!masterColumnType.equals(currentColumnType)){
            //1.varchar和char 可以构建关联
            String[] varcharArr = {"CHAR","VARCHAR"};
        }
        return true;
    }*/

    /**
     * 删除键
     *
     * @param dynaBean 自定义动态类
     * @param ids      ID列表
     * @param ddl      执行的DDL
     * @return
     */
    @Override
    @Transactional
    public Integer removeKey(DynaBean dynaBean, String ids, String ddl) throws UncategorizedSQLException {
        String[] split = ids.split(ArrayUtils.SPLIT);
        DynaBean table = metaService.selectOneByPk("JE_CORE_TABLEKEY", split[0]);
        String tablecode = table.getStr("TABLEKEY_TABLECODE");
        List<DynaBean> keys = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEKEY")
                .in("JE_CORE_TABLEKEY_ID", split));
        for (int i = 0; i < keys.size(); i++) {
            DynaBean key = keys.get(i);
            if ("Primary".equals(key.get("TABLEKEY_TYPE"))) {
                return -1;
            }
            metaTableTraceService.saveTableTrace("JE_CORE_TABLEKEY", key, "DELETE", key.getStr("TABLEKEY_RESOURCETABLE_ID"), key.getStr("TABLEKEY_ISCREATE"));
        }

        deleteKey(tablecode, keys, ddl);
        tableCache.removeCache(tablecode);
        dynaCache.removeCache(tablecode);
        return keys.size();
    }


}
